package com.avic.rong.search.fragment.searchResultFragments;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.BaseFragment;
import com.avic.rong.R;
import com.avic.rong.bean.show_bean.EsInfoBean;
import com.avic.rong.fragment.showapi.EsInfoApi;
import com.avic.rong.goodsSort.bean.showRvBean.GoodsSortSearchAllBzBean;
import com.avic.rong.search.MessageEvent;
import com.avic.rong.search.activity.SearchResaultActivity;
import com.avic.rong.search.adapter.searchResultFragmentsAdapters.SearchArticleRvAdapter;
import com.avic.rong.search.adapter.searchResultFragmentsAdapters.SearchBzShrinkRvAdapter;
import com.avic.rong.search.adapter.searchResultFragmentsAdapters.SearchGoodsShrinkRvAdapter;
import com.avic.rong.search.adapter.searchResultFragmentsAdapters.SearchPeiXunShrinkRvAdapter;
import com.avic.rong.search.adapter.searchResultFragmentsAdapters.SearchVpPeiXunRvAdapter;
import com.avic.rong.search.adapter.searchResultFragmentsAdapters.SearchWendaShrinkRvAdapter;
import com.avic.rong.search.api.secondViewApi.SearchHomeQuanBuApi;
import com.avic.rong.userOrder.api.AddCarApi;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DeviceUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class SearchQuanBuFragment extends BaseFragment implements
        SearchBzShrinkRvAdapter.SearchHomePageQuanBuBzListener,
        SearchGoodsShrinkRvAdapter.SearchHomePageQuanBuGoodsListener,
        SearchPeiXunShrinkRvAdapter.SearchHomePagePeiXunListener {


    @BindView(R.id.search_QuanBu_Tv_ShowMore_BiaoZhun)
    TextView searchQuanBuTvShowMoreBiaoZhun;
    @BindView(R.id.home_page_RelativeLayout_Bz)
    RelativeLayout homePageRelativeLayoutBz;
    @BindView(R.id.home_page_RecyclerView_Bz)
    RecyclerView homePageRecyclerViewBz;
    @BindView(R.id.search_QuanBu_Tv_ShowMore_Goods)
    TextView searchQuanBuTvShowMoreGoods;
    @BindView(R.id.home_page_RelativeLayout_Goods)
    RelativeLayout homePageRelativeLayoutGoods;
    @BindView(R.id.home_page_RecyclerView_Goods)
    RecyclerView homePageRecyclerViewGoods;
    @BindView(R.id.beijing_image)
    ImageView beijing_image;

    @BindView(R.id.home_page_RecyclerView_Article)
    RecyclerView homePageRecyclerViewArticle;
    @BindView(R.id.search_QuanBu_Tv_ShowMore_PeiXun)
    TextView searchQuanBuTvShowMorePeiXun;
    @BindView(R.id.home_page_RelativeLayout_PeiXun)
    RelativeLayout homePageRelativeLayoutPeiXun;
    @BindView(R.id.home_page_RecyclerView_PeiXun)
    RecyclerView homePageRecyclerViewPeiXun;
    @BindView(R.id.search_vp_quanbu_tv)
    TextView searchVpQuanbuTv;
    @BindView(R.id.home_page_ScrollView)
    ScrollView homePageScrollView;
    @BindView(R.id.search_fragment_quanbu_SmartRefreshLayout)
    SmartRefreshLayout searchFragmentQuanbuSmartRefreshLayout;

    @BindView(R.id.home_page_quanbu_tv_nomore)
    TextView homePageQuanbuTvNomore;
    private View view;
    Unbinder unbinder;

    private SearchGoodsShrinkRvAdapter homePageGoodsRvAdapter;
    private SearchBzShrinkRvAdapter homePageBzRvAdapter;
    private SearchVpPeiXunRvAdapter homePagePeiXunRvAdapter;

    private List<GoodsSortSearchAllBzBean.DataBean> homePageQuanBuBzList = new ArrayList<>();
    private List<GoodsSortSearchAllBzBean.DataBean> homePageQuanBuGoodsList = new ArrayList<>();
    private List<GoodsSortSearchAllBzBean.DataBean> homePageQuanBuPeiXunList = new ArrayList<>();
    private List<GoodsSortSearchAllBzBean.DataBean> homePageQuanBuArticleList = new ArrayList<>();
    private List<GoodsSortSearchAllBzBean.DataBean> homePageQuanBuWenDaList = new ArrayList<>();
    private ArrayList<EsInfoBean> esList=new ArrayList<>();
    String currentText = "GJB";
    //分开使用
    private static int pageNo = 1;
    //下面文章专属
    private static int pagenum = 1;
    private SearchResaultActivity searchResaultActivity;
    private SearchWendaShrinkRvAdapter homePagePeiXunRvAdapter1;
    private SearchArticleRvAdapter homePageArticleRvAdapter1;
    private List<GoodsSortSearchAllBzBean.DataBean> listWen = new ArrayList<>();
    private SearchHomeQuanBuApi searchWenzhang;
    private ArrayList<EsInfoBean> esInfoBean;
    public SearchQuanBuFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_search_quan_bu, container, false);
        unbinder = ButterKnife.bind(this, view);
        searchResaultActivity = new SearchResaultActivity();
        Bundle arguments = this.getArguments();
        if (arguments != null)
            currentText = arguments.getString("nowSearchStr");
        currentText = SearchResaultActivity.nowSearchStr;
        homePageRecyclerViewArticle.setLayoutManager(new LinearLayoutManager(getActivity()));
        pageNo = 1;
        pagenum = 1;
        listWen.clear();
        homePageArticleRvAdapter1=new SearchArticleRvAdapter(getActivity(),listWen,esList);
        homePageRecyclerViewArticle.setAdapter(homePageArticleRvAdapter1);
        homePageRecyclerViewGoods.setNestedScrollingEnabled(false);
        homePageRecyclerViewBz.setNestedScrollingEnabled(false);
        homePageRecyclerViewArticle.setNestedScrollingEnabled(false);
        homePageRecyclerViewPeiXun.setNestedScrollingEnabled(false);
        initQuanBuData(currentText, pageNo);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        setRefresh();
        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MesssageEventBus(MessageEvent event) {
        listWen.clear();
        HttpManager.getInstance().doHttpDeal(searchWenzhang);
    }
    //搜索补全接口
    HttpOnNextListener<BaseResultEntity> EnsOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            String code = baseResultEntity.getCode();
            if (code.equals("200")) {
                esInfoBean = (ArrayList<EsInfoBean>) baseResultEntity.getData();
                esList.addAll(esInfoBean);
                homePageArticleRvAdapter1.notifyDataSetChanged();
            } else {

            }
        }
    };
    //获取文章
    HttpOnNextListener<BaseResultEntity> searchWenZhangListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals("200")) {

                Log.e("cjx", "biaozhun数据：" + subjects.getMsg());
                return;
            }
            ArrayList<GoodsSortSearchAllBzBean> searchHomeQuanBuList = (ArrayList<GoodsSortSearchAllBzBean>) subjects.getData();
            listWen.addAll(searchHomeQuanBuList.get(3).getData());
            if (listWen.size() > 0) {
                homePageRecyclerViewArticle.setVisibility(View.VISIBLE);
                String substring="";
                String countId="";
                for (int i = 0; i < listWen.size(); i++) {
                    int dataId = listWen.get(i).getDataId();
                    countId+=dataId+",";
                }
                substring=countId.substring(0,countId.length()-1);
                EsInfoApi esInfoApi = new EsInfoApi((RxAppCompatActivity) getActivity(), EnsOnNextListener, substring);
                esInfoApi.setCache(false);
                HttpManager.getInstance().doHttpDeal(esInfoApi);
            } else {
                homePageRecyclerViewArticle.setVisibility(View.GONE);

            }
        }

        @Override
        public void onCacheNext(String cache) {
        }

        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", "bz拿到数据" + e.getMessage());
        }
    };
    private void setRefresh() {
        searchFragmentQuanbuSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                pagenum=1;
                listWen.clear();
                setAllHomePageListClear();
                initQuanBuData(currentText, pageNo);
                searchWenzhang = new SearchHomeQuanBuApi((RxAppCompatActivity) getActivity(), searchWenZhangListener, "quanbu", 5, currentText, pagenum, 10);
                searchWenzhang.setCache(false);
                HttpManager.getInstance().doHttpDeal(searchWenzhang);
                searchFragmentQuanbuSmartRefreshLayout.finishRefresh(1000);
            }
        });
        searchFragmentQuanbuSmartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                ++pagenum;
                searchWenzhang = new SearchHomeQuanBuApi((RxAppCompatActivity) getActivity(), searchWenZhangListener, "quanbu", 5, currentText, pagenum, 10);
                searchWenzhang.setCache(false);
                HttpManager.getInstance().doHttpDeal(searchWenzhang);
                searchFragmentQuanbuSmartRefreshLayout.finishLoadMore(1000);
            }
        });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        currentText = SearchResaultActivity.nowSearchStr;
        Log.e("cjx", "SearchQuanBuFragment--------currentText:" + currentText);
    }

    public void initQuanBuData(String keyword, int pageNo) {
        SearchHomeQuanBuApi searchAllApi = new SearchHomeQuanBuApi((BaseActivity) getActivity(), searchHomeQuanBuListener, "quanbu", 0, keyword, pageNo, 10);
        Log.e("cjx", "bzkeyWord:" + keyword);
        searchAllApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(searchAllApi);

        searchWenzhang = new SearchHomeQuanBuApi((RxAppCompatActivity) getActivity(), searchWenZhangListener, "quanbu", 5, currentText, pagenum, 5  );
        searchWenzhang.setCache(false);
        HttpManager.getInstance().doHttpDeal(searchWenzhang);
    }

    //获取标准数据监听
    HttpOnNextListener<BaseResultEntity> searchHomeQuanBuListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals("200")) {

                Log.e("cjx", "biaozhun数据：" + subjects.getMsg());
                return;
            }
            setAllHomePageListClear();
            ArrayList<GoodsSortSearchAllBzBean> searchHomeQuanBuList = (ArrayList<GoodsSortSearchAllBzBean>) subjects.getData();
            homePageQuanBuBzList.addAll(searchHomeQuanBuList.get(0).getData());
            homePageQuanBuGoodsList.addAll(searchHomeQuanBuList.get(1).getData());
            homePageQuanBuPeiXunList.addAll(searchHomeQuanBuList.get(2).getData());
            homePageQuanBuArticleList.addAll(searchHomeQuanBuList.get(3).getData());
            if (searchHomeQuanBuList.get(4)!=null){
                homePageQuanBuWenDaList.addAll(searchHomeQuanBuList.get(4).getData());
            }
          if (homePageQuanBuBzList.size()==0&&homePageQuanBuGoodsList.size()==0&&homePageQuanBuPeiXunList.size()==0&&homePageQuanBuArticleList.size()==0){
              searchVpQuanbuTv.setVisibility(View.VISIBLE);
              beijing_image.setVisibility(View.VISIBLE);
              homePageQuanbuTvNomore.setVisibility(View.GONE);
          }else{
              searchVpQuanbuTv.setVisibility(View.GONE);
              beijing_image.setVisibility(View.GONE);
              homePageQuanbuTvNomore.setVisibility(View.VISIBLE);
          }
//            if (searchHomeQuanBuList.get(4).getData())
            //标准
            if (homePageQuanBuBzList.size() > 0) {
                homePageRecyclerViewBz.setVisibility(View.VISIBLE);
                homePageRelativeLayoutBz.setVisibility(View.VISIBLE);
                homePageRecyclerViewBz.setLayoutManager(new LinearLayoutManager(getActivity()));
                homePageBzRvAdapter = new SearchBzShrinkRvAdapter(getContext(), homePageQuanBuBzList);
                homePageRecyclerViewBz.setAdapter(homePageBzRvAdapter);
                homePageBzRvAdapter.setListener(SearchQuanBuFragment.this);
            } else {
                homePageRecyclerViewBz.setVisibility(View.GONE);
                homePageRelativeLayoutBz.setVisibility(View.GONE);
            }
            //商品
            if (homePageQuanBuGoodsList.size() > 0) {
                homePageRecyclerViewGoods.setVisibility(View.VISIBLE);
                homePageRelativeLayoutGoods.setVisibility(View.VISIBLE);

                homePageRecyclerViewGoods.setLayoutManager(new LinearLayoutManager(getActivity()));
                homePageGoodsRvAdapter = new SearchGoodsShrinkRvAdapter(getContext(), homePageQuanBuGoodsList);
                homePageRecyclerViewGoods.setAdapter(homePageGoodsRvAdapter);
                homePageGoodsRvAdapter.setListener(SearchQuanBuFragment.this);
            } else {
                homePageRecyclerViewGoods.setVisibility(View.GONE);
                homePageRelativeLayoutGoods.setVisibility(View.GONE);
            }

            //培训
            if (homePageQuanBuPeiXunList.size() > 0) {
                homePageRecyclerViewPeiXun.setVisibility(View.VISIBLE);
                homePageRelativeLayoutPeiXun.setVisibility(View.VISIBLE);

                homePageRecyclerViewPeiXun.setLayoutManager(new LinearLayoutManager(getActivity()));
                homePagePeiXunRvAdapter = new SearchVpPeiXunRvAdapter(context, homePageQuanBuPeiXunList);
                homePageRecyclerViewPeiXun.setAdapter(homePagePeiXunRvAdapter);

            } else {
                homePageRecyclerViewPeiXun.setVisibility(View.GONE);
                homePageRelativeLayoutPeiXun.setVisibility(View.GONE);
            }
//            //问答
//            if (homePageQuanBuWenDaList.size() > 0){
//
//                homePageRecyclerViewWenda.setVisibility(View.VISIBLE);
//                homePageRelativeLayoutWenda.setVisibility(View.VISIBLE);
//
//                homePageRecyclerViewWenda.setLayoutManager(new LinearLayoutManager(getActivity()));
//                homePagePeiXunRvAdapter1 = new SearchWendaShrinkRvAdapter(context, homePageQuanBuWenDaList);
//                homePageRecyclerViewWenda.setAdapter(homePagePeiXunRvAdapter1);
//
//            } else {
//                homePageRecyclerViewWenda.setVisibility(View.GONE);
//                homePageRelativeLayoutWenda.setVisibility(View.GONE);
//            }


        }

        @Override
        public void onCacheNext(String cache) {
        }

        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", "bz拿到数据" + e.getMessage());
        }
    };

    private void setAllHomePageListClear() {
        homePageQuanBuBzList.clear();
        homePageQuanBuGoodsList.clear();
        homePageQuanBuPeiXunList.clear();
        homePageQuanBuArticleList.clear();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void addListener() {

    }

    @Override
    protected int getContentViewId() {
        return 0;
    }

    @OnClick({R.id.search_QuanBu_Tv_ShowMore_BiaoZhun, R.id.search_QuanBu_Tv_ShowMore_Goods,R.id.search_QuanBu_Tv_ShowMore_PeiXun})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_QuanBu_Tv_ShowMore_BiaoZhun:
                EventBus.getDefault().post(new MessageEvent("1"));
                break;
            case R.id.search_QuanBu_Tv_ShowMore_Goods:
                EventBus.getDefault().post(new MessageEvent("3"));
                break;
            case R.id.search_QuanBu_Tv_ShowMore_PeiXun:
                EventBus.getDefault().post(new MessageEvent("2"));
                break;

        }
    }

    private void AddCar(String skuStr) {
        Log.e("cjx", "skuStr:" + skuStr);

            Map<String, String> map = new HashMap<>();
            map.put("skuStr", skuStr);
            map.put("orderType", 4 + "");
//            是否再次购买（0/1）
            map.put("buyAgain", 0 + "");
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            map.put("token", SharedPreferencesUtil.getLoginToken());
        }
            map.put("deviceId", DeviceUtils.getIMEString(context));
            final AddCarApi addCarApi = new AddCarApi((SearchResaultActivity) getActivity(), simpleOnNextListenerAddCar);
            addCarApi.setCache(false);
            addCarApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(addCarApi);

    }

    //添加购物车
    HttpOnNextListener simpleOnNextListenerAddCar = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {

                return;
            }
            ToastTools.showToast("添加成功");
        }

        @Override
        public void onCacheNext(String cache) {
        }

        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    @Override
    public void searchHomePageQuanBuBzAddCar(String skuStr) {
        AddCar(skuStr);
    }

    @Override
    public void addGoodsCar(String skuStr) {
        AddCar(skuStr);
    }



    @Override
    public void searchPeiXunClick(int index) {

    }

}
